// 农场数据

// 土地容器dom
var landWrap;
// 所有土地dom
var landItems;
// 作物成熟倒计时
var landTimes;

// 作物容器
var cropWrap;
// 所有作物dom
var cropItems;

// 所有仓库物品dom
var houseItems;
// 仓库容器dom
var houseWrap;
// 仓库格子索引
var houseCellIndex = 1;
// 仓库当前页面
var housePageIndex = 1;
// 仓库页面数量
var housePageIndexMax;
// 仓库左边按钮
var houseLeftBtn;
// 仓库右边按钮
var houseRightBtn;
// 仓库种子按钮
var houseSeedBtn;
// 仓库果实按钮
var houseCropBtn;
// 仓库当前页是果实还是种子
var houseCropOrSeed;
// 仓库当前页是果实还是种子类型
var houseCropOrSeedType;

//钻石收割容器
var diamondRipeWrap;
// 签到按钮
var signinPic;

// 种子容器dom
var seedWrap;
// 所有种子dom
var seedItems;
// 种子当前页面
var seedPageIndex = 1;
// 种子页面的最大值
var seedPageIndexMax;

// 点击作物容器dom
var clickCropWrap;
// 所有点击项dom
var clickCropItems;

// 种子数组
var seedArr = [];
// 作物数组
var cropArr = [];
// 所有种子数组
var seedArrAll = [];

// 收割庄稼容器
var reapCropWrap;
// 收割庄稼时的土地索引
var reapCropLandIndex = null;

// 等级
var levelNumber;
// 金币
var coinNumber;
// 钻石
var diamondNumber;
// 经验
var expNumber;
// 当前级别最大经验
var expMaxNumber;
// 仓库售出物品容器
var houseSaleWrap;

// 购买种子容器
var buySeedWrap;
//售出视图容器
var saleWrap;
// 购买种子当前页面
var buySeedPageIndex = 1;
// 购买种子页面最大值
var buySeedPageIndexMax;
// 购买种子格子索引
var buySeedCellIndex = 1;
// 当前出售物品
var good;
// 当前购买种子
var buySeed;
// 可收获动画dom数组
var reapAni;
// 可扩建动画dom数组
var extendAni;

//音频
var audioMain;
var audioClick;
var audioPlant;
var audioReap;
var audioUpgrade;
// 是否开启声音
var audioMainState = false;
var audioClickState = true;

// 主场景
var mainScene;

(function () {
    var mainViewStr = `
        <div id="main-scene">
            <div id="main-land-wrap">
                <div id="land-crop-wrap">
                    <ul id="land-wrap">
                        <li class="land-item0"><div class="land-time"></div></li>
                        <li class="land-item1"><div class="land-time"></div></li>
                        <li class="land-item2"><div class="land-time"></div></li>
                        <li class="land-item3"><div class="land-time"></div></li>
                        <li class="land-item4"><div class="land-time"></div></li>
                        <li class="land-item5"><div class="land-time"></div></li>
                        <li class="land-item6"><div class="land-time"></div></li>
                        <li class="land-item7"><div class="land-time"></div></li>
                        <li class="land-item8"><div class="land-time"></div></li>
                        <li class="land-item9"><div class="land-time"></div></li>
                        <li class="land-item10"><div class="land-time"></div></li>
                        <li class="land-item11"><div class="land-time"></div></li>
                        <li class="land-item12"><div class="land-time"></div></li>
                        <li class="land-item13"><div class="land-time"></div></li>
                        <li class="land-item14"><div class="land-time"></div></li>
                        <li class="land-item15"><div class="land-time"></div></li>
                        <li class="land-item16"><div class="land-time"></div></li>
                        <li class="land-item17"><div class="land-time"></div></li>
                        <li class="land-item18"><div class="land-time"></div></li>
                        <li class="land-item19"><div class="land-time"></div></li>
                        <li class="land-item20"><div class="land-time"></div></li>
                        <li class="land-item21"><div class="land-time"></div></li>
                        <li class="land-item22"><div class="land-time"></div></li>
                        <li class="land-item23"><div class="land-time"></div></li>
                    </ul>
                    <ul id="crop-wrap">
                        <li class="crop-item0"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item1"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item2"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item3"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item4"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item5"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item6"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item7"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item8"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item9"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item10"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item11"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item12"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item13"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item14"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item15"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item16"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item17"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item18"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item19"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item20"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item21"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item22"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                        <li class="crop-item23"><div class="reap-ani"></div><div class="extend-ani"></div></li>
                    </ul>
                    <ul id="click-crop-wrap">
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                        <li class="click-crop-item"></li>
                    </ul>
                    <div id="mine-pic">
                        <div class="info">xx:xx</div>
                        <div class="mine-ani"></div>
                    </div>
                </div>
            </div>
            <div id="signin-pic"></div>
            <div id="house-pic"></div>
            <div id="shop-pic"></div>
            <div id="upgrade-land-pic"></div>
            <div id="setting-pic"></div>
            <div id="house-wrap">
                <div id="house-content">
                    <span class="houseTitle">仓库（100）</span>
                    <div class="house-crop">果实（100）</div>
                    <div class="house-seed">种子（100）</div>
                    <ul>    
                        <div id="house-crop-wrap"></div>
                        <div id="house-seed-wrap"></div>
                    </ul>
                    <span class="house-page">0/0</span>
                    <div class="leftBtn">👈</div>
                    <div class="rightBtn">👉</div>
                    <img src="images/main/close.png" class="house-close">
                </div>
            </div>
            <div id="seed-wrap">
                <ul>
                    <li>
                        <div class="seed-itemm"></div>
                        <div class="seed-item-name"></div>
                        <button>购买</button>
                    </li>
                    <li>
                        <div class="seed-itemm"></div>
                        <div class="seed-item-name"></div>
                        <button>购买</button>
                    </li>
                    <li>
                        <div class="seed-itemm"></div>
                        <div class="seed-item-name"></div>
                        <button>购买</button>
                    </li>
                    <li>
                        <div class="seed-itemm"></div>
                        <div class="seed-item-name"></div>
                        <button>购买</button>
                    </li>
                    <li>
                        <div class="seed-itemm"></div>
                        <div class="seed-item-name"></div>
                        <button>购买</button>
                    </li>
                </ul>
                <div class="leftBtn">👈</div>
                <div class="rightBtn">👉</div>
            </div>
            <div class="diamond-ripe-wrap">
                <div class="diamond-click">
                    <img src="images/main/diamond.png">
                    <div class="reap-name">钻石立即成熟</div>
                </div>
            </div>
            <div id="upgrade-land-wrap">
                <div class="setting-content">
                    <div class="close"></div>
                    <div class="title">
                        <p>升级土地</p>
                        <ul>
                            <li class="btn active">红土地</li>
                            <li class="btn">黑土地</li>
                            <li class="btn">蓝土地</li>
                            <li class="btn">紫土地</li>
                            <li class="btn">金土地</li>
                        </ul>
                    </div>
                    <ul class="content">
                        <li class="item active">
                            <div class="plain-land"></div>
                            <div class="arrow">→</div>
                            <div class="land land-right">红土地?</div>
                            <div class="info"></div>
                            <button>升级土地</button>
                        </li>
                        <li class="item">
                            <div class="land">红土地?</div>
                            <div class="arrow">→</div>
                            <div class="land land-right">黑土地?</div>
                            <div class="info"></div>
                            <button>升级土地</button>
                        </li>
                        <li class="item">
                            <div class="land">黑土地?</div>
                            <div class="arrow">→</div>
                            <div class="land land-right">蓝土地?</div>
                            <div class="info"></div>
                            <button>升级土地</button>
                        </li>
                        <li class="item">
                            <div class="land">蓝土地?</div>
                            <div class="arrow">→</div>
                            <div class="land land-right">紫土地?</div>
                            <div class="info"></div>
                            <button>升级土地</button>
                        </li>
                        <li class="item">
                            <div class="land">紫土地?</div>
                            <div class="arrow">→</div>
                            <div class="land land-right">金土地?</div>
                            <div class="info"></div>
                            <button>升级土地</button>
                        </li>
                    </ul>
                </div>
            </div>
            <div id="setting-wrap">
                <div class="setting-content">
                    <div class="close"></div>
                    <div class="title">
                        <p>系统设置</p>
                        <ul>
                            <li class="btn active">游戏公告</li>
                            <li class="btn">声音设置</li>
                            <li class="btn">修改密码</li>
                            <li class="btn">留言反馈</li>
                        </ul>
                    </div>
                    <ul class="content">
                        <li class="item active">
                            <div class="public-wrap">
                                <h3>游戏公告</h3>
                                <div class="public-con"></div>
                            </div>
                        </li>
                        <li class="item">
                            <div class="audio-wrap">
                                <button class="item-music1">音乐<div class="red-line"></div></button>
                                <button class="item-music2">音效<div class="red-line"></div></button>
                                <button class="item-music-save">保存</button>
                            </div>
                        </li>
                        <li class="item">
                            <div class="update-pwd-wrap">
                                <table>
                                    <caption>修改密码</caption>
                                    <tr>
                                        <td>旧密码：</td>
                                        <td><input type="password"></td>
                                        <td>
                                            <div class="del-text">×</div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>新密码：</td>
                                        <td><input type="password"></td>
                                        <td>
                                            <div class="del-text">×</div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>确认密码：</td>
                                        <td><input type="password"></td>
                                        <td>
                                            <div class="del-text">×</div>
                                        </td>
                                    </tr>
                                </table>
                                <input type="submit" value="更新">
                            </div>
                        </li>
                        <li class="item">
                            <div class="advise-wrap">
                                <textarea placeholder="在游戏中遇到的任何问题以及发现游戏的Bug或者有好的建议反馈都可以随时与我们取得联系，我们非常欢迎您的留言！"></textarea>
                                <br>
                                <button>提交</button>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div id="reap-crop-wrap">
                <div class="reap-crop">
                    <img src="images/main/sickle.png">
                    <div class="reap-name">收割</div>
                </div>
            </div>
            <div id="coin-wrap">
                <span><strong id="levelNumber">0级</strong><img src="images/main/exp.png"><strong>×</strong><strong id="expNumber">0</strong><strong>/</strong><strong id="expMaxNumber">9999</strong></span>
                <span><img src="images/main/coin.png"><strong>×</strong><strong id="coinNumber">0</strong></span>
                <span><img src="images/main/diamond.png"> <strong>×</strong> <strong id="diamondNumber">0</strong></span>
            </div>
            <div id="sale-wrap">
                <div class="sale-item">
                    <div class="img"></div>
                    <div class="sale">
                        <button class="sub">-</button>
                        <input type="number" min=1 value=1 max=999 class="number">
                        <button class="add">+</button>
                        <button class="all">全部</button>
                        <br>
                        <div class="sale-coin">卷心菜种子 - 100, 金币 + 100000</div>
                        <button class="sale-part">售出</button>
                        <button class="sale-cancer">取消</button>
                    </div>
                </div>
            </div>
            <div id="buy-seed-wrap">
                <div class="sale-item">
                    <div class="img"></div>
                    <div class="sale">
                        <button class="sub">-</button>
                        <input type="number" min=1 value=1 max=999 class="number">
                        <button class="add">+</button>
                        <button class="all">+10</button>
                        <br>
                        <div class="sale-coin">卷心菜种子 - 100, 金币 + 100000</div>
                        <button class="sale-part">购买</button>
                        <button class="sale-cancer">取消</button>
                    </div>
                </div>
            </div>
        </div>
    `;


    var div = document.createElement('div');
    div.innerHTML = mainViewStr;
    div = div.firstElementChild;
    mainView = div;

    //钻石收割容器
    diamondRipeWrap = mainView.querySelector('.diamond-ripe-wrap');
    // 签到图标容器
    signinPic = mainView.querySelector('#signin-pic');

    //获取24块土地
    mainScene = div; //获取主场景dom
    var mainLandWrap = mainScene.querySelector('#main-land-wrap');
    landWrap = mainScene.querySelector('#land-wrap');
    landItems = landWrap.querySelectorAll('[class^=land-item]');
    landTimes = landWrap.querySelectorAll('.land-time');
    //获取24个作物
    cropWrap = mainScene.querySelector('#crop-wrap');
    cropItems = cropWrap.querySelectorAll('[class^=crop-item]');
    //获取24个点击作物
    clickCropWrap = mainScene.querySelector('#click-crop-wrap');
    clickCropItems = clickCropWrap.querySelectorAll('[class^=click-crop-item]');

    //初始化土地、作物、点击作物位置
    for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 4; j++) {
            var index = i * 4 + j;
            var leftPos = (i + 3 - j) * 60 / 50;
            var bottomPos = (7.9 - i - j) * 30 / 50;
            //初始化土地位置
            landItems[index].style.left = leftPos + 'rem';
            landItems[index].style.bottom = bottomPos + 'rem';
            //初始化作物位置
            cropItems[index].style.left = leftPos + 'rem';
            cropItems[index].style.bottom = bottomPos + 0.05 + 'rem';
            //初始化点击作物位置
            clickCropItems[index].style.left = leftPos + 0.4 + 'rem';
            clickCropItems[index].style.bottom = bottomPos + 'rem';
            clickCropItems[index].index = index;
        }
    }

    //买种子视图
    buySeedWrap = mainScene.querySelector('#buy-seed-wrap');

    //点击土地弹出按钮
    var wrapDiv = document.createElement('div');
    wrapDiv.style.width = '2rem';
    wrapDiv.style.height = '2rem';
    wrapDiv.style.backgroundColor = 'deeppink';
    wrapDiv.style.borderRadius = '50%';

    //售出视图
    saleWrap = mainView.querySelector('#sale-wrap');

    //点击仓库图标，弹出仓库
    var housePic = mainScene.querySelector('#house-pic');
    houseWrap = mainScene.querySelector('#house-wrap');
    housePic.onclick = function () {
        audioClickPlay();
        houseWrap.style.display = 'block';
        clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
        seedWrap.style.display = 'none';
        reapCropWrap.style.display = 'none';
    }
    var shopPic = mainScene.querySelector('#shop-pic');
    shopPic.onclick = function () {
        audioClickPlay();
        reapCropLandIndex = -1;
        clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
        seedWrap.style.display = 'block';
    }

    //点击物品卖出
    houseWrap.onclick = function (e) {
        if (e.target.id === 'house-wrap') {
            houseWrap.style.display = 'none';
        } else if (e.target.className === 'house-item') {
            audioClickPlay();
            houseCellIndex = e.target.parentNode.index;
            // 仓库物品索引值
            var houseGoodIndex = (housePageIndex - 1) * 10 + houseCellIndex;
            good = houseCropOrSeed[houseGoodIndex];
            drawSaleGoodView();
        }
    }
    houseWrap.querySelector('.house-close').onclick = function () {
        audioClickPlay();
        houseWrap.style.display = 'none';
    }

    //渲染出售物品视图
    function drawSaleGoodView() {
        saleWrap.querySelector('.number').value = 1;

        var img = saleWrap.querySelector('.img');
        if (houseCropOrSeed === cropArr) {
            img.style.background = 'url(images/product/' + good.ID + '.png) no-repeat';
        } else if (houseCropOrSeed === seedArr) {
            img.style.background = 'url(images/crop/' + good.ID + '.png) no-repeat center -0.3rem';
        }
        img.style.backgroundSize = '2rem 2rem';
        img.style.backgroundColor = '#fff';

        var number = saleWrap.querySelector('.number');
        var saleCoin = saleWrap.querySelector('.sale-coin');

        saleCoin.innerHTML = '卖出 ' + good.name + ' 获得金币 × ' + (parseInt(number.value) * good.saleprice);

        saleWrap.style.display = 'block';
    }

    //出售物品注册点击事件
    saleWrap.onclick = function (e) {
        var number = this.querySelector('.number');
        var saleCoin = this.querySelector('.sale-coin');
        var saleMaxNumber = findGoodNumberByGoodID(good.ID);

        if (e.target === this) {
            this.style.display = 'none';
        } else if (e.target.className === 'sub') {
            audioClickPlay();
            if (parseInt(number.value) > 1) {
                number.value = parseInt(number.value) - 1;
            }

            saleCoin.innerHTML = '卖出 ' + good.name + ' 获得金币 × ' + (parseInt(number.value) * good.saleprice);
        } else if (e.target.className === 'add') {
            audioClickPlay();
            if (parseInt(number.value) < saleMaxNumber) {
                number.value = parseInt(number.value) + 1;
                saleCoin.innerHTML = '卖出 ' + good.name + ' 获得金币 × ' + (parseInt(number.value) * good.saleprice);
            }
        } else if (e.target.className === 'all') {
            audioClickPlay();
            number.value = saleMaxNumber;
            saleCoin.innerHTML = '卖出 ' + good.name + ' 获得金币 ' + (parseInt(number.value) * good.saleprice);
        } else if (e.target.className === 'sale-part') {
            audioClickPlay();
            var goodID = good.ID;
            var saleGoodNumber = parseInt(number.value) <= saleMaxNumber ? parseInt(number.value) : saleMaxNumber;

            $.ajax({
                "url": "sql.asp",
                "type": "post",
                "data": {
                    action: 'saleGood',
                    ID: gameDatas.ID,
                    goodID: goodID,
                    saleNumber: saleGoodNumber
                },
                "dataType": "text",
                "success": function (data) {
                    var jsonData = JSON.parse(data)
                    if (jsonData.state === 'ok') {
                        //卖出物品成功
                        var addCoin = jsonData.addCoin;
                        gameDatas.house[findHouseIndexByGoodID(goodID)].number = jsonData.remainNumber;
                        addCoinNumber(jsonData.addCoin);
                        popMessage('<img src="images/main/coin.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 金币 + ' + addCoin);

                        //更新金币、等级等数据
                        drawCoinExpDiamond();
                        //取得 种子数组 和 作物数组
                        getSeedsAndCrops();
                        //更新houseCropOrSeed
                        houseCropOrSeed = houseCropOrSeedType === 'crop' ? cropArr : seedArr;
                        //渲染仓库视图
                        drawHouseAndGoods(houseCropOrSeedType);
                        //渲染背包种子视图
                        drawBagSeedView();
                        //渲染是否可扩建土地视图
                        drawLandExtendFun(true);
                    } else if (jsonData.state === 'stop') {
                        gamescene.innerHTML = '<img src="images/fg.jpg" style="height: 100%; position: absolute;">';
                        gamescene.appendChild(loginView);
                        popMessage(jsonData.msg);
                    } else if (jsonData.state === 'error') {
                        popMessage(jsonData.msg);
                    } else {
                        popMessage(ajaxDataError);
                    }
                },
                "error": function () {
                    popMessage(ajaxError);
                }
            });

            this.style.display = 'none';
        } else if (e.target.className === 'sale-cancer') {
            audioClickPlay();
            this.style.display = 'none';
        }
    }

    //初始化仓库物品
    houseItems = houseWrap.querySelectorAll('[class^=house-item]');

    //初始化仓库左右按钮
    houseLeftBtn = houseWrap.querySelector('.leftBtn');
    houseRightBtn = houseWrap.querySelector('.rightBtn');

    //初始化背包种子列表
    seedWrap = mainScene.querySelector('#seed-wrap');
    seedItems = seedWrap.querySelectorAll('.seed-itemm');
    seedItemNames = seedWrap.querySelectorAll('.seed-item-name');

    //收割庄稼容器
    reapCropWrap = mainScene.querySelector('#reap-crop-wrap');

    //注册点击作物事件
    mainLandWrap.onclick = function (e) {
        if (e.target.className === "click-crop-item" || e.target.className === "reap-ani" || e.target.className === "extend-ani") {
            clickCropFun(e.target.index);
        } else {
            seedWrap.style.display = 'none';
            diamondRipeWrap.style.display = 'none';

            clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
            reapCropWrap.style.display = 'none';
            setRipeTime(false);
        }
    }

    //仓库种子、果实按钮
    houseSeedBtn = houseWrap.querySelector('.house-seed');
    houseCropBtn = houseWrap.querySelector('.house-crop');

    //级别、金币、钻石、经验dom
    levelNumber = mainView.querySelector('#levelNumber');
    coinNumber = mainView.querySelector('#coinNumber');
    diamondNumber = mainView.querySelector('#diamondNumber');
    expNumber = mainView.querySelector('#expNumber');
    expMaxNumber = mainView.querySelector('#expMaxNumber');
})();

// 点击了作物执行的函数
function clickCropFun(index) {
    audioClickPlay();
    reapCropLandIndex = index;

    clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
    clickCropItems[index].classList.add('active');
    if (gameDatas.lands[index].type === 'lock') {
        reapCropWrap.style.display = 'none';
        diamondRipeWrap.style.display = 'none';

        if (gameDatas.level < gameDatas.plainLevel) {
            // 等级不足
            popDialog('扩建新土地需要等级' + gameDatas.plainLevel + '级、花费' + gameDatas.plainCoin + '金币，您的等级不足', 1);
        } else if (gameDatas.coin < gameDatas.plainCoin) {
            popDialog('扩建新土地需要等级' + gameDatas.plainLevel + '级、花费' + gameDatas.plainCoin + '金币，您的金币不足', 1);
        } else {
            popDialog('扩建新土地需要等级' + gameDatas.plainLevel + '级、花费' + gameDatas.plainCoin + '金币，您确定要扩建吗？', 2, function () {
                extendLandFun(index);
            });
        }
        // popMessage('扩建土地需要金币和等级满足条件哦');
    } else if (gameDatas.lands[index].type === "grass") {
        reapCropWrap.style.display = 'none';
        popMessage('未开垦的草地');
    } else {
        if (gameDatas.lands[index].GID === -1) {
            // 土地上无作物
            seedWrap.style.display = 'block';
            reapCropWrap.style.display = 'none';
        } else if (gameDatas.lands[index].planttime <= 0) {
            // 作物已成熟
            reapCropWrap.style.display = 'block';
            reapCropWrap.querySelector('.reap-name').innerHTML = '收割 ' + gameDatas.goods[findGoodIndexByGoodID(gameDatas.lands[index].GID)].name;
            //隐藏种植种子视图
            seedWrap.style.display = 'none';
            diamondRipeWrap.style.display = 'none';
        } else if (gameDatas.lands[index].planttime > 0) {
            // 作物在生长中
            setRipeTime(true);
            seedWrap.style.display = 'none';
            reapCropWrap.style.display = 'none';
            popMessage(gameDatas.goods[findGoodIndexByGoodID(gameDatas.lands[index].GID)].name + ' 正在生长中');
            diamondRipeWrap.style.display = 'block';
        }
    }
}

//渲染购买种子视图
function drawBuySeedView() {
    var number = buySeedWrap.querySelector('.number');
    number.value = 1;
    //背包物品索引值
    var buySeedIndex = (buySeedPageIndex - 1) * 5 + buySeedCellIndex;
    // 欲购买的种子
    buySeed = seedArrAll[buySeedIndex];
    var img = buySeedWrap.querySelector('.img');
    img.style.background = 'url(images/crop/' + buySeed.ID + '.png) no-repeat center -0.3rem';

    img.style.backgroundSize = '2rem 2rem';
    img.style.backgroundColor = '#fff';

    var saleCoin = buySeedWrap.querySelector('.sale-coin');

    saleCoin.innerHTML = '购买 ' + buySeed.name + ' 所需金币 × ' + (parseInt(number.value) * buySeed.buyprice);

    buySeedWrap.style.display = 'block';
}

//渲染不同类型的土地和在土地上种植的作物视图      ok
function drawLandAndCrop() {
    for (let i = 0; i < gameDatas.lands.length; i++) {
        landItems[i].style.background = 'url(images/land/land_' + gameDatas.lands[i].type + '.png) no-repeat';
        landItems[i].style.backgroundSize = '2rem 1rem';

        // 找到goods的ID为gameDatas.land[i].GID，渲染庄稼
        // 如果该土地为未解锁状态，则不应该有作物出现在它上面
        if (gameDatas.lands[i].type != 'lock') {
            if (gameDatas.lands[i].GID === -1) {
                //土地空闲
                cropItems[i].style.background = '';
                cropItems[i].style.backgroundSize = '2rem 2rem';
            } else {
                cropItems[i].style.background = 'url(images/crop/' + gameDatas.lands[i].GID + '.png) no-repeat';
                cropItems[i].style.backgroundSize = '2rem 2rem';
            }
        }
    }
}



//渲染仓库视图        ok
function drawHouseAndGoods(type) {
    //渲染仓库
    if (type == 'crop') {
        houseCropOrSeed = cropArr;
        houseCropOrSeedType = 'crop';
        drawHouseItems();
        houseWrap.querySelector('#house-crop-wrap').style.display = 'block';
        houseWrap.querySelector('#house-seed-wrap').style.display = 'none';
    } else if (type == 'seed') {
        houseCropOrSeed = seedArr;
        houseCropOrSeedType = 'seed';
        drawHouseItems();
        houseWrap.querySelector('#house-crop-wrap').style.display = 'none';
        houseWrap.querySelector('#house-seed-wrap').style.display = 'block';
    }

    houseWrap.querySelector('.house-crop').innerHTML = '果实（' + cropArr.length + '）';
    houseWrap.querySelector('.house-seed').innerHTML = '种子（' + seedArr.length + '）';
    houseWrap.querySelector('.houseTitle').innerHTML = '仓库（' + (cropArr.length + seedArr.length) + '）';
}

//初始化主界面数据      ok
function initMainViewDatas() {

    upgradeLandInit();

    getUpgradeAfterDatas(function () {
        //进入游戏主界面
        gamescene.innerHTML = '';
        gamescene.appendChild(mainView);

        // 可收获提示框点击事件
        initReapExtendFun();

        //渲染土地和其上的作物视图
        drawLandAndCrop();

        // 矿山
        mineInit();
        drawLandsTime();

        // 渲染可扩建土地提示
        drawLandExtendFun(true);

        //初始化金币、等级等数据
        drawCoinExpDiamond()

        //取得 种子数组 和 作物数组
        getSeedsAndCrops()

        //渲染仓库视图
        houseCropOrSeedType = 'crop';
        drawHouseAndGoods(houseCropOrSeedType);

        //渲染背包种子视图
        drawBagSeedView();

        audioMain = new Audio('music/main.html');
        audioClick = new Audio('music/click.html');
        audioPlant = new Audio('music/plant.html');
        audioReap = new Audio('music/reap.html');
        audioUpgrade = new Audio('music/upgrade.html');
        audioMain.preload = true;

        //播放音频
        if (audioMainState) {
            audioClickPlay();
            audioMain.loop = 'loop';
        }

        // 设置模块
        settingInit();
        // 设置音效

        // 检测是否有用户的新回复
        checkReply();
    })
}

// 扩建土地函数
function extendLandFun(landIndex) {
    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'extendLand',
            ID: gameDatas.ID,
            landIndex: landIndex
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data)
            if (jsonData.state === 'ok') {
                //成功返回数据
                // 隐藏已扩建的土地的提示
                drawLandExtendFun(false);
                addCoinNumber(jsonData.addCoin);
                gameDatas.lands[landIndex].type = 'plain';
                getUpgradeAfterDatas(function () {
                    if (landIndex >= 23) {
                        popMessage('土地已全部扩建完毕');
                    } else {
                        popMessage('<img src="images/land/land_plain.png" style="width:1.6rem;height:0.8rem;vertical-align:middle;"> 土地 + 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/main/coin.png" style="width:0.8rem;height:0.8rem;vertical-align:middle;"> 金币 - ' + Math.abs(jsonData.addCoin));
                        gameDatas.lands[landIndex + 1].type = 'lock';
                        drawLandExtendFun(true);
                    }
                    drawLandsTime();
                    audioReapPlay();
                    drawLandAndCrop();
                });
            } else if (jsonData.state === 'error') {
                popMessage(jsonData.msg);
            } else {
                popMessage(ajaxDataError);
            }
        },
        "error": function () {
            popMessage(ajaxError);
        }
    });
}

// 可收获提示框点击事件
function initReapExtendFun() {
    reapAni = gamescene.querySelectorAll('#crop-wrap .reap-ani');
    extendAni = gamescene.querySelectorAll('#crop-wrap .extend-ani');
    for (let i = 0; i < 24; i++) {
        reapAni[i].index = i;
        extendAni[i].index = i;
    }
}


//渲染仓库在不同页面的物品，参数是物品类型和页面
function drawHouseItems() {

    // 仓库所有物品数量
    var houseAllItemsNumber = houseCropOrSeed.length;

    // 仓库页面数量
    housePageMaxIndex = houseAllItemsNumber === 0 ? 1 : Math.floor((houseAllItemsNumber + -1) / 10) + 1;
    // 当前仓库格子的数量
    var houseCellNumber = housePageIndex != housePageMaxIndex ? 10 : houseAllItemsNumber - (housePageIndex - 1) * 10;

    //渲染格子
    var houseWrapUL;
    if (houseCropOrSeedType === 'crop') {
        houseWrapUL = houseWrap.querySelector('ul').querySelector('#house-crop-wrap');
    } else if (houseCropOrSeedType === 'seed') {
        houseWrapUL = houseWrap.querySelector('ul').querySelector('#house-seed-wrap');
    }
    houseWrapUL.innerHTML = '';


    //仓库当前页面物品索引值
    var houseNowIndex = (housePageIndex - 1) * 10;
    for (let i = 0; i < houseCellNumber; i++) {
        var divViewStr = `
            <li class="house-li">
                <div class="house-item"></div>
                <div class="house-gold">
                    <span class="item"></span>
                </div>
            </li>
        `;
        var div = document.createElement('div');
        div.innerHTML = divViewStr;
        div = div.children[0];
        div.index = i;
        var houseItemDIV = div.querySelector('[class^=house-item]');
        var info = div.querySelector('.item');
        if (houseCropOrSeed === cropArr) {
            houseItemDIV.style.background = 'url(images/product/' + cropArr[houseNowIndex].ID + '.png) no-repeat';
        } else if (houseCropOrSeed === seedArr) {
            houseItemDIV.style.background = 'url(images/crop/' + seedArr[houseNowIndex].ID + '.png) no-repeat center -0.2rem';
        }
        info.innerHTML = houseCropOrSeed[houseNowIndex].name + ' × ' + gameDatas.house[findHouseIndexByGoodID(houseCropOrSeed[houseNowIndex].ID)].number;
        houseItemDIV.style.backgroundSize = '1.5rem 1.5rem';
        houseItemDIV.style.backgroundColor = '#fff';
        houseNowIndex++;
        houseWrapUL.appendChild(div);
    }
    // 渲染当前页面显示和页面数量
    houseWrap.querySelector('.house-page').innerHTML = housePageIndex + '/' + housePageMaxIndex;

    if (housePageMaxIndex === 1) {
        houseLeftBtn.style.display = 'none';
        houseRightBtn.style.display = 'none';
    } else if (housePageIndex === 1) {
        houseLeftBtn.style.display = 'none';
        houseRightBtn.style.display = 'block';
    } else if (housePageIndex === housePageMaxIndex) {
        houseLeftBtn.style.display = 'block';
        houseRightBtn.style.display = 'none';
    } else {
        houseLeftBtn.style.display = 'block';
        houseRightBtn.style.display = 'block';
    }
}


//仓库左侧按钮点击事件
houseLeftBtn.onclick = function () {
    audioClickPlay();
    housePageIndex--;
    drawHouseAndGoods(houseCropOrSeedType);
}

//仓库右侧按钮点击事件
houseRightBtn.onclick = function () {
    audioClickPlay();
    housePageIndex++;
    drawHouseAndGoods(houseCropOrSeedType);
    houseLeftBtn.style.display = 'block';
}


//指定背包跳转到指定页
function drawBagSeedView() {
    var seedAllNumber = seedArrAll.length; //所有的种子数量
    buySeedPageIndexMax = Math.floor((seedAllNumber - 1) / 5) + 1; //种子最大页面
    // 当前购买种子索引
    var seedListIndex = (buySeedPageIndex - 1) * 5; //

    //当前页面种子数量的最大值
    var buySeedNowPageMax = buySeedPageIndex === buySeedPageIndexMax ? seedAllNumber - seedListIndex : 5;

    var seedLI = seedWrap.querySelectorAll('li');

    for (let i = 0; i < 5; i++) {
        seedLI[i].style.display = 'none';
    }
    var seedBtns = seedWrap.querySelectorAll('button');
    for (let i = 0; i < buySeedNowPageMax; i++) {
        seedLI[i].style.display = 'block';
        seedLI[i].classList.remove('lock');
        seedItems[i].style.background = 'url(images/crop/' + seedArrAll[seedListIndex + i].ID + '.png) no-repeat center bottom';
        seedItems[i].style.backgroundSize = '1.5rem 1.5rem';
        seedItems[i].style.backgroundColor = '#fff';
        seedItems[i].index = i;
        seedBtns[i].index = i;
        seedItems[i].parentNode.querySelector('.seed-item-name').innerHTML = seedArrAll[seedListIndex + i].name + '<br>* ' + findGoodNumberByGoodID(seedArrAll[seedListIndex + i].ID);
    }
    if (buySeedPageIndex === buySeedPageIndexMax && (gameDatas.level <= 14)) {
        seedLI[buySeedNowPageMax - 1].style.display = 'block';
        seedLI[buySeedNowPageMax - 1].classList.add('lock');
        seedItems[buySeedNowPageMax - 1].style.background = 'url(images/crop/' + seedArrAll[seedListIndex + buySeedNowPageMax - 1].ID + '.png) no-repeat center bottom';
        seedItems[buySeedNowPageMax - 1].style.backgroundSize = '1.5rem 1.5rem';
        seedItems[buySeedNowPageMax - 1].style.backgroundColor = '#fff';
        seedItems[buySeedNowPageMax - 1].index = buySeedNowPageMax - 1;
        seedItems[buySeedNowPageMax - 1].parentNode.querySelector('.seed-item-name').innerHTML = seedArrAll[seedListIndex + buySeedNowPageMax - 1].name;
    }


    var left = seedWrap.querySelector('.leftBtn');
    var right = seedWrap.querySelector('.rightBtn');
    if (buySeedPageIndexMax === 1) {
        left.style.display = 'none';
        right.style.display = 'none';
    } else if (buySeedPageIndex === 1) {
        left.style.display = 'none';
        right.style.display = 'block';
    } else if (buySeedPageIndex === buySeedPageIndexMax) {
        left.style.display = 'block';
        right.style.display = 'none';
    } else {
        left.style.display = 'block';
        right.style.display = 'block';
    }
}

//取得 种子数组 和 作物数组
function getSeedsAndCrops() {
    seedArr = [];
    cropArr = [];
    seedArrAll = [];

    for (let i = 0; i < gameDatas.house.length; i++) {
        var crop = gameDatas.goods[findGoodIndexByGoodID(gameDatas.house[i].ID)];

        if (gameDatas.house[i].number > 0) {
            if (crop.type === 'seed') {
                //是种子
                seedArr.push(crop);
            } else if (crop.type === 'crop') {
                //是产品
                cropArr.push(crop);
            }
        }

        if (crop.type === 'seed') {
            seedArrAll.push(crop);
        }
    }
    seedArrAll = seedArrAll.filter(function (item, index) {
        return index <= gameDatas.level && index <= 15;
    })
    houseCropOrSeed = cropArr;
}

seedWrap.querySelector('.leftBtn').onclick = function () {
    audioClickPlay();
    if (buySeedPageIndex > 1) {
        buySeedPageIndex--;
        drawBagSeedView();
    }
}

seedWrap.querySelector('.rightBtn').onclick = function () {
    audioClickPlay();
    if (buySeedPageIndex < buySeedPageIndexMax) {
        buySeedPageIndex++;
        drawBagSeedView();
    }
}

houseSeedBtn.onclick = function () {
    audioClickPlay();
    this.style.backgroundColor = 'red';
    this.style.boxShadow = '0.1rem 0.1rem 0.05rem 0.05rem #fff';
    houseWrap.querySelector('.house-crop').style.backgroundColor = '#aaa';
    houseWrap.querySelector('.house-crop').style.boxShadow = '0 0 0 0 #fff';
    housePageIndex = 1;
    houseCropOrSeed = seedArr;
    houseCropOrSeedType = 'seed';
    drawHouseItems();
    houseWrap.querySelector('#house-seed-wrap').style.display = 'block';
    houseWrap.querySelector('#house-crop-wrap').style.display = 'none';
}

houseCropBtn.onclick = function () {
    audioClickPlay();
    this.style.backgroundColor = 'red';
    this.style.boxShadow = '0.1rem 0.1rem 0.05rem 0.05rem #fff';
    houseWrap.querySelector('.house-seed').style.backgroundColor = '#aaa';
    houseWrap.querySelector('.house-seed').style.boxShadow = '0 0 0 0 #fff';
    housePageIndex = 1;
    houseCropOrSeed = cropArr;
    houseCropOrSeedType = 'crop';
    drawHouseItems();
    houseWrap.querySelector('#house-seed-wrap').style.display = 'none';
    houseWrap.querySelector('#house-crop-wrap').style.display = 'block';
}

//收割庄稼容器点击事件
mainView.querySelector('#reap-crop-wrap').onclick = function (e) {
    if (e.target.className === 'reap-crop' || e.target.tagName === 'IMG') {
        audioClickPlay();
        clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
        reapCropFun(reapCropLandIndex);

        clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
        var flag = true;
        for (let i = reapCropLandIndex + 1; i < 24; i++) {
            if (gameDatas.lands[i].type != 'lock' && gameDatas.lands[i].type != 'grass' && gameDatas.lands[i].GID != -1 && gameDatas.lands[i].planttime <= 0) {
                reapCropLandIndex = i;
                clickCropItems[i].classList.add('active');
                flag = false;
                break;
            }
        }
        if (flag) {
            reapCropWrap.style.display = 'none';
        }
    }
}
//钻石成熟容器点击事件
diamondRipeWrap.onclick = function (e) {
    if (e.target.className === 'diamond-click' || e.target.tagName === 'IMG') {
        audioClickPlay();
        clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');

        var landID = gameDatas.lands[reapCropLandIndex].ID;
        var goodID = gameDatas.lands[reapCropLandIndex].GID;
        var diamondI = gameDatas.goods[findGoodIndexByGoodID(goodID)].diamondripeprice;
        if (gameDatas.diamond < diamondI) {
            popMessage('钻石不足');
            return;
        }

        popDialog('确定要用钻石立即成熟吗？', 2, () => {
            $.ajax({
                "url": "sql.asp",
                "type": "post",
                "data": {
                    action: 'diamondReap',
                    ID: gameDatas.ID,
                    landID: landID
                },
                "dataType": "text",
                "success": function (data) {
                    var jsonData = JSON.parse(data);
                    if (jsonData.state === 'ok') {
                        popMessage('作物已成熟， <img src="images/main/diamond.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"></img> 钻石 - ' + (gameDatas.diamond - jsonData.diamond));
                        gameDatas.lands[reapCropLandIndex].planttime = 0;
                        addDiamond(jsonData.diamond - gameDatas.diamond);
                    } else if (jsonData.state === 'error') {
                        popMessage(jsonData.msg);
                    } else {
                        popMessage(ajaxDataError);
                    }
                },
                "error": function () {
                    popMessage(ajaxError);
                }
            });
            diamondRipeWrap.style.display = 'none';
        })
    }
}


//收割庄稼，参数是土地索引#############################################################
function reapCropFun(landIndex) {
    var landID = gameDatas.lands[landIndex].ID;
    var goodID = gameDatas.lands[landIndex].GID;

    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'reapCrop',
            ID: gameDatas.ID,
            landID: landID
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data);
            if (jsonData.state === 'ok') {
                gameDatas.house[findHouseIndexByGoodID(goodID)].number += jsonData.addNumber;
                var cropName = gameDatas.goods[findGoodIndexByGoodID(goodID)].name;
                gameDatas.lands[landIndex].GID = -1;
                gameDatas.plainLand = jsonData.plainLand;
                landTimes[landIndex].innerHTML = '空闲';

                //播放收割音效
                audioReapPlay();
                //渲染土地和其上的作物视图
                drawLandAndCrop();
                drawLandsTime();
                //增加经验
                addExp(jsonData.addExp, jsonData.isUpgrade == 'true', jsonData.expMax);

                //取得 种子数组 和 作物数组
                getSeedsAndCrops();
                //渲染仓库视图
                drawHouseAndGoods(houseCropOrSeedType);

                popMessage('<img src="images/product/' + goodID + '.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> ' + cropName + ' + ' + jsonData.addNumber + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/main/exp.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 经验 + ' + jsonData.addExp);
            } else if (jsonData.state === 'error') {
                popMessage(jsonData.msg);
            } else {
                popMessage(ajaxDataError);
            }
        },
        "error": function () {
            popMessage(ajaxError);
        }
    });
}

// 升级函数
function upgradeFun() {
    popDialog('<h2 style="text-align:center;color: red;">升级啦</h2><div style="text-align: center;margin-top: 0.2rem;">恭喜您升到<span style="position:relative;top:-0.05rem;font-weight: bold;font-size: 0.6rem;vertical-align:middle;color: rgb(255,215,0);">' + gameDatas.level + '</span>级</div>', 0, null, true);
    var foreward = document.querySelector('#foreward');
    foreward.style.display = 'block';
    var t = 40;
    var timer;
    timer && clearInterval(timer);
    timer = setInterval(() => {
        addParticlesAtRandomPoint();
        t--;
        if (t === 0) {
            clearInterval(timer);
            foreward.style.display = 'none';
        }
    }, 100);
    audioUpgradePlay();
    setTimeout(() => {
        audioUpgradePlay();
    }, 2000);
    getSeedsAndCrops();
    drawBagSeedView();
    drawLandExtendFun(true);
}

// 升级后获取数据
function getUpgradeAfterDatas(callback) {
    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'getUpgradeAfterDatas',
            ID: gameDatas.ID
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data);
            if (jsonData.state === 'ok') {
                gameDatas.plainLevel = jsonData.plainLevel;
                gameDatas.plainCoin = jsonData.plainCoin;
                gameDatas.redLevel = jsonData.redLevel;
                gameDatas.redCoin = jsonData.redCoin;
                gameDatas.blackLevel = jsonData.blackLevel;
                gameDatas.blackCoin = jsonData.blackCoin;
                gameDatas.blueLevel = jsonData.blueLevel;
                gameDatas.blueCoin = jsonData.blueCoin;
                gameDatas.purpleLevel = jsonData.purpleLevel;
                gameDatas.purpleCoin = jsonData.purpleCoin;
                gameDatas.goldLevel = jsonData.goldLevel;
                gameDatas.goldCoin = jsonData.goldCoin;

                callback && callback();

            } else if (jsonData.state === 'finish') {
                gameDatas.plainLevel = -1;
                gameDatas.plainCoin = -1;
                callback && callback();
            } else if (jsonData.state === 'error') {
                popMessage(jsonData.msg);
            } else {
                popMessage(ajaxDataError);
            }
        },
        "error": function () {
            popMessage(ajaxError);
        }
    });
}

//修改金币、经验、钻石等数据
function addCoinNumber(num) {
    gameDatas.coin += num;
    coinNumber.innerHTML = gameDatas.coin;
}

function addDiamond(num) {
    gameDatas.diamond += num;
    diamondNumber.innerHTML = gameDatas.diamond;
}

function updateLevel(isUpgrade) {
    if (isUpgrade && gameDatas.level <= 99) {
        gameDatas.level++;
    }
    levelNumber.innerHTML = gameDatas.level + '级';
}

function addExp(num, isUpgrade, expMax) {
    gameDatas.exp += num;
    if (isUpgrade) {
        if (gameDatas.level <= 99) {
            updateLevel(true);
            gameDatas.exp -= gameDatas.expMax;
            updateExpMax(expMax);
            upgradeFun();
        }
    }
    if (gameDatas.level >= 100) {
        gameDatas.exp = 'max';
        updateExpMax('max');
    }
    expNumber.innerHTML = gameDatas.exp;
}

function updateExpMax(num) {
    gameDatas.expMax = num;
    expMaxNumber.innerHTML = num;
}

//渲染金币、经验等数据
function drawCoinExpDiamond() {
    addCoinNumber(0);
    addDiamond(0);
    updateLevel(false);
    addExp(0);
    updateExpMax(gameDatas.expMax);
}

//物品ID    ->      数组里的索引
function findGoodIndexByGoodID(goodID) {
    for (let i = 0; i < gameDatas.goods.length; i++) {
        if (goodID === gameDatas.goods[i].ID) {
            return i;
        }
    }
}

//作物ID    ->      仓库的索引
function findHouseIndexByGoodID(goodID) {
    for (let i = 0; i < gameDatas.house.length; i++) {
        if (gameDatas.house[i].ID === goodID) {
            return i;
        }
    }
}

//作物ID    ->      作物的数量
function findGoodNumberByGoodID(goodID) {
    for (let i = 0; i < gameDatas.house.length; i++) {
        if (gameDatas.house[i].ID === goodID) {
            return gameDatas.house[i].number;
        }
    }
}


//种植作物#####################################################################################
function plantCrop(landIndex, goodID) {
    var landID = gameDatas.lands[landIndex].ID;

    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'plantCrop',
            ID: gameDatas.ID,
            landID: landID,
            goodID: goodID
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data);
            if (jsonData.state === 'ok') {
                gameDatas.house[findHouseIndexByGoodID(goodID)].number = jsonData.seednumber;
                gameDatas.lands[landIndex].GID = goodID;
                popMessage(gameDatas.goods[findHouseIndexByGoodID(goodID)].name + ' 种植成功');
                audioPlantPlay();

                gameDatas.lands[landIndex].planttime = gameDatas.goods[findGoodIndexByGoodID(goodID)].ripetime * 60;
                landTimes[landIndex].innerHTML = Math.floor(gameDatas.lands[landIndex].planttime / 3600 % 60) + ":" + Math.floor(gameDatas.lands[landIndex].planttime / 60 % 60) + ":" + Math.floor(gameDatas.lands[landIndex].planttime % 60);

                landItems[landIndex].timer && clearInterval(landItems[landIndex].timer);
                landItems[landIndex].timer = setInterval(function () {
                    gameDatas.lands[landIndex].planttime--;
                    landTimes[landIndex].innerHTML = Math.floor(gameDatas.lands[landIndex].planttime / 3600 % 60) + ":" + Math.floor(gameDatas.lands[landIndex].planttime / 60 % 60) + ":" + Math.floor(gameDatas.lands[landIndex].planttime % 60);
                    if (gameDatas.lands[landIndex].planttime <= 0) {
                        clearInterval(landItems[landIndex].timer);
                        gameDatas.lands[landIndex].planttime = 0;
                        landTimes[landIndex].innerHTML = '可收获';
                        reapAni[landIndex].style.display = 'block';
                        gameDatas.lands[landIndex].GID = goodID + 1;
                        drawLandAndCrop();
                    }
                }, 1000)

                //渲染土地和其上的作物视图
                drawLandAndCrop();
                //取得 种子数组 和 作物数组
                getSeedsAndCrops();
                //渲染仓库视图
                drawHouseAndGoods(houseCropOrSeedType);
                //渲染背包种子视图
                drawBagSeedView();
            } else if (jsonData.state === 'error') {
                popMessage(jsonData.msg);
            } else {
                popMessage(ajaxDataError);
            }
        },
        "error": function () {
            popMessage(ajaxError);
        }
    });
}

//点击种子事件
seedWrap.onclick = function (e) {
    if (e.target.className === 'seed-itemm') {
        audioClickPlay();
        // 种植种子
        if (reapCropLandIndex == null || reapCropLandIndex < 0 || reapCropLandIndex > 23) {
            popMessage('请选择一块土地');
        } else if (gameDatas.lands[reapCropLandIndex].type === 'lock' || gameDatas.lands[reapCropLandIndex].type === 'grass') {
            popMessage('土地未扩建，无法种植');
        } else if (gameDatas.lands[reapCropLandIndex].GID === -1) {
            // 土地空闲，可以种植
            var seedIndex = (buySeedPageIndex - 1) * 5 + e.target.index;
            if (seedIndex >= gameDatas.level && seedIndex < 15) {
                popMessage('种子未解锁');
                return;
            }
            buySeed = seedArrAll[seedIndex];
            if (findGoodNumberByGoodID(buySeed.ID) > 0) {
                plantCrop(reapCropLandIndex, buySeed.ID);
                clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
                var flag = true;
                for (let i = reapCropLandIndex + 1; i < 24; i++) {
                    if (gameDatas.lands[i].type != 'lock' && gameDatas.lands[i].type != 'grass' && gameDatas.lands[i].GID === -1) {
                        reapCropLandIndex = i;
                        clickCropItems[i].classList.add('active');
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    seedWrap.style.display = 'none';
                }
            } else {
                popMessage('没有该种子了');
            }
        } else {
            popMessage('土地不是空闲状态');
        }
    } else if (e.target.tagName === 'BUTTON') {
        audioClickPlay();
        // 购买种子
        var seedIndex = (buySeedPageIndex - 1) * 5 + e.target.index;
        buySeed = seedArrAll[seedIndex];
        buySeedCellIndex = e.target.index;

        if (gameDatas.coin < buySeed.buyprice) {
            popMessage('金币不足');
            return;
        }

        drawBuySeedView();
    }
}
//种子背包点击购买按钮事件
buySeedWrap.onclick = function (e) {

    var number = this.querySelector('.number');
    var saleCoin = this.querySelector('.sale-coin');

    if (e.target === this) {
        this.style.display = 'none';
    } else if (e.target.className === 'sub') {
        audioClickPlay();
        if (parseInt(number.value) > 1) {
            number.value = parseInt(number.value) - 1;
        }
        saleCoin.innerHTML = '购买 ' + buySeed.name + ' 所需金币 × ' + (parseInt(number.value) * buySeed.buyprice);
    } else if (e.target.className === 'add') {
        audioClickPlay();
        if (gameDatas.coin < (parseInt(number.value) + 1) * buySeed.buyprice) {
            popMessage('金币不足');
            return;
        }
        number.value = parseInt(number.value) + 1;
        saleCoin.innerHTML = '购买 ' + buySeed.name + ' 所需金币 × ' + (parseInt(number.value) * buySeed.buyprice);
    } else if (e.target.className === 'all') {
        audioClickPlay();
        for (let i = 0; i < 10; i++) {
            if (gameDatas.coin >= (parseInt(number.value) + 1) * buySeed.buyprice) {
                number.value = parseInt(number.value) + 1;
            } else {
                popMessage('金币不足');
                break;
            }
        }
        saleCoin.innerHTML = '购买 ' + buySeed.name + ' 所需金币 × ' + (parseInt(number.value) * buySeed.buyprice);
    } else if (e.target.className === 'sale-part') {
        audioClickPlay();
        var seedID = buySeed.ID;
        var buySeedNumber = parseInt(number.value);
        //购买种子

        $.ajax({
            "url": "sql.asp",
            "type": "post",
            "data": {
                action: 'buySeed',
                ID: gameDatas.ID,
                seedID: seedID,
                buySeedNumber: buySeedNumber
            },
            "dataType": "text",
            "success": function (data) {
                var jsonData = JSON.parse(data);
                if (jsonData.state === 'ok') {
                    //成功返回数据
                    gameDatas.house[findHouseIndexByGoodID(seedID)].number += buySeedNumber;
                    addCoinNumber(jsonData.addCoin);
                    popMessage('<img src="images/main/coin.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 金币' + ' - ' + Math.abs(jsonData.addCoin));
                    //初始化金币、等级等数据
                    drawCoinExpDiamond();
                    //取得 种子数组 和 作物数组
                    getSeedsAndCrops();
                    //渲染仓库视图
                    drawHouseAndGoods(houseCropOrSeedType);
                    //渲染背包种子视图
                    drawBagSeedView();
                    //渲染是否可扩建土地视图
                    drawLandExtendFun(true);
                } else if (jsonData.state === 'error') {
                    popMessage(jsonData.msg);
                } else {
                    popMessage(ajaxDataError);
                }
            },
            "error": function () {
                popMessage(ajaxError);
            }
        });
        this.style.display = 'none';
    } else if (e.target.className === 'sale-cancer') {
        audioClickPlay();
        buySeedWrap.style.display = 'none';
    }
}

//设置倒计时状态
function setRipeTime(flag) {
    for (let i = 0; i < landTimes.length; i++) {
        if (flag) {
            landTimes[i].style.display = 'block';
        } else {
            landTimes[i].style.display = 'none';
        }
    }
}

// 遍历所有土地的种植状态
function drawLandsTime() {
    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'getLandsState',
            ID: gameDatas.ID
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data)
            if (jsonData.state === 'ok') {
                for (let i = 0; i < gameDatas.lands.length; i++) {
                    gameDatas.lands[i].planttime = jsonData[i + ''] ? jsonData[i + ''] : 0;
                }

                for (let i = 0; i < 24; i++) {
                    if (gameDatas.lands[i].type === 'grass') {
                        landTimes[i].innerHTML = '草地';
                    } else if (gameDatas.lands[i].type === 'lock') {
                        landTimes[i].innerHTML = '未扩建';
                    } else if (gameDatas.lands[i].GID === -1) {
                        landTimes[i].innerHTML = '空闲';
                        reapAni[i].style.display = 'none';
                    } else if (gameDatas.lands[i].planttime <= 0) {
                        landTimes[i].innerHTML = '可收获';
                        reapAni[i].style.display = 'block';
                        if (gameDatas.lands[i].GID % 2 === 1) {
                            gameDatas.lands[i].GID++;
                            drawLandAndCrop();
                        }
                    } else if (gameDatas.lands[i].planttime > 0) {
                        landTimes[i].innerHTML = Math.floor(gameDatas.lands[i].planttime / 3600) + ":" + Math.floor(gameDatas.lands[i].planttime / 60 % 60) + ":" + Math.floor(gameDatas.lands[i].planttime % 60);
                        landItems[i].timer && clearInterval(landItems[i].timer);
                        landItems[i].timer = setInterval(function () {
                            gameDatas.lands[i].planttime--;
                            landTimes[i].innerHTML = Math.floor(gameDatas.lands[i].planttime / 3600) + ":" + Math.floor(gameDatas.lands[i].planttime / 60 % 60) + ":" + Math.floor(gameDatas.lands[i].planttime % 60);
                            if (gameDatas.lands[i].planttime <= 0) {
                                clearInterval(landItems[i].timer);
                                gameDatas.lands[i].planttime = 0;
                                gameDatas.lands[i].GID++;
                                landTimes[i].innerHTML = '可收获';
                                reapAni[i].style.display = 'block';
                                drawLandAndCrop();
                            }
                        }, 1000)
                    }
                }

                // 矿山
                gameDatas.mine = jsonData.mine;
                if (gameDatas.mine <= 0) {
                    mineInfo.innerHTML = '可收取';
                    mainScene.querySelector('.mine-ani').style.display = 'block';
                } else {
                    mineInfo.innerHTML = gameDatas.mine;
                    mineInfo.innerHTML = Math.floor(gameDatas.mine / 3600 % 60) + ":" + Math.floor(gameDatas.mine / 60 % 60) + ":" + Math.floor(gameDatas.mine % 60);
                    gameDatas.mineTimer && clearInterval(gameDatas.mineTimer);
                    gameDatas.mineTimer = setInterval(() => {
                        gameDatas.mine--;
                        mineInfo.innerHTML = Math.floor(gameDatas.mine / 3600 % 60) + ":" + Math.floor(gameDatas.mine / 60 % 60) + ":" + Math.floor(gameDatas.mine % 60);
                        if (gameDatas.mine <= 0) {
                            clearInterval(gameDatas.mineTimer);
                            mineInfo.innerHTML = '可收取';
                            mainScene.querySelector('.mine-ani').style.display = 'block';
                        }
                    }, 1000);
                }
                //渲染是否可扩建土地视图
                drawLandExtendFun(true);
            } else {
                popMessage(jsonData.msg);
            }
        }
    });
}

// 渲染土地的可扩建状态
function drawLandExtendFun(isShow) {
    var lockIndex;
    for (let i = 0; i < gameDatas.lands.length; i++) {
        if (gameDatas.lands[i].type === 'lock') {
            lockIndex = i;
            break;
        }
    }
    if (gameDatas.plainLevel !== -1) {
        if (isShow && gameDatas.level >= gameDatas.plainLevel && gameDatas.coin >= gameDatas.plainCoin) {
            // 提示扩建土地
            extendAni[lockIndex].style.display = 'block';
        } else {
            // 隐藏扩建土地提示
            extendAni[lockIndex].style.display = 'none';
        }
    }
}

// 播放点击音效
function audioClickPlay() {
    audioClick && audioClickState && audioClick.play();
}

// 播放种植庄稼音效
function audioPlantPlay() {
    if (audioPlant && audioClickState) {
        audioPlant.currentTime = 0;
        audioPlant.play();
    }
}

// 播放收割庄稼音效
function audioReapPlay() {
    if (audioReap && audioClickState) {
        audioReap.currentTime = 0;
        audioReap.play();
    }
}

// 播放升级音效
function audioUpgradePlay() {
    if (audioUpgrade && audioClickState) {
        audioUpgrade.currentTime = 0;
        audioUpgrade.play();
    }
}

// 关闭种子商店
function closeSeedWrap() {
    seedWrap.style.display = 'none';
    reapCropWrap.style.display = 'none';
}

// 清除点击作物
function clearClickCircleView() {
    reapCropLandIndex = -1;
    clickCropWrap.querySelector('.active') && clickCropWrap.querySelector('.active').classList.remove('active');
}


// 设置模块
function settingInit() {
    var settingPic = mainScene.querySelector('#setting-pic');
    var settingWrap = mainScene.querySelector('#setting-wrap');
    var btns = settingWrap.querySelectorAll('.title .btn');
    var items = settingWrap.querySelectorAll('.item');
    var delTexts = settingWrap.querySelectorAll('.update-pwd-wrap .del-text');
    var updatePwdBtn = settingWrap.querySelector('.update-pwd-wrap input[type=submit]');

    settingPic.onclick = function () {
        audioClickPlay();
        settingWrap.style.display = 'block';
        closeSeedWrap();
        clearClickCircleView();
    }

    for (let i = 0; i < btns.length; i++) {
        btns[i].onclick = function () {
            audioClickPlay();
            this.parentNode.querySelector('.btn.active').classList.remove('active');
            this.classList.add('active');
            items[i].parentNode.querySelector('.item.active').classList.remove('active');
            items[i].classList.add('active');
        }
    }

    // 关闭按钮
    settingWrap.querySelector('.close').onclick = function () {
        audioClickPlay();
        settingWrap.style.display = 'none';
    }

    //公告模块
    var publicCon = settingWrap.querySelector('.public-con');
    publicCon.innerHTML = gameDatas.public;

    // 声音设置
    var itemMusic1 = settingWrap.querySelector('.item-music1');
    var itemMusic2 = settingWrap.querySelector('.item-music2');
    var itemMusicSave = settingWrap.querySelector('.item-music-save');
    var redLine1 = itemMusic1.querySelector('.red-line:first-child');
    var redLine2 = itemMusic2.querySelector('.red-line:last-child');
    itemMusic1.onclick = function () {
        if (redLine1.classList.contains('active')) {
            redLine1.classList.remove('active');
            audioMainState = true;
            // 播放背景音乐
            if (audioMain) {
                audioMain.currentTime = 0;
                audioMain.play();
                audioMain.loop = 'loop';
            }
        } else {
            redLine1.classList.add('active');
            audioMainState = false;
            // 停止播放背景音乐
            audioMain && audioMain.pause();
        }
    }
    itemMusic2.onclick = function () {
        if (redLine2.classList.contains('active')) {
            // 开启音效
            redLine2.classList.remove('active');
            audioClickState = true;
        } else {
            // 关闭音效
            redLine2.classList.add('active');
            audioClickState = false;
        }
        audioClickPlay();
    }
    itemMusicSave.onclick = function () {
        // 保存声音设置到数据库

        $.ajax({
            "url": "sql.asp",
            "type": "post",
            "data": {
                action: 'setMusic',
                ID: gameDatas.ID,
                musicbg: audioMainState,
                musicclick: audioClickState
            },
            "dataType": "text",
            "success": function (data) {
                var jsonData = JSON.parse(data)
                if (jsonData.state === 'ok') {
                    // 保存音乐状态成功
                    popMessage('保存成功');
                } else if (jsonData.state === 'error') {
                    popMessage(jsonData.msg);
                } else {
                    popMessage(ajaxDataError);
                }
            },
            "error": function () {
                popMessage(ajaxError);
            }
        });
        audioClickPlay();
    }

    // 设置音效
    musicInit();

    function musicInit() {
        // 背景音乐
        gameDatas.musicbg == 'true' ? setMusicBgView(true) : setMusicBgView(false);

        // 音效
        gameDatas.musicclick == 'true' ? setMusicClickView(true) : setMusicClickView(false);
    }

    // 设置背景音乐视图
    function setMusicBgView(state) {
        if (state) {
            // 播放背景音乐
            redLine1.classList.remove('active');
            audioMainState = true;
            if (audioMain) {
                audioMain.currentTime = 0;
                audioMain.play();
                audioMain.loop = 'loop';
            }
        } else {
            // 不播放背景音乐
            redLine1.classList.add('active');
            audioMainState = false;
            audioMain && audioMain.pause();
        }
    }

    //设置音效视图
    function setMusicClickView(state) {
        if (state) {
            // 开启音效
            redLine2.classList.remove('active');
            audioClickState = true;
        } else {
            // 关闭音效
            redLine2.classList.add('active');
            audioClickState = false;
        }
    }

    // 修改密码模块
    for (let i = 0; i < delTexts.length; i++) {
        delTexts[i].onclick = function () {
            audioClickPlay();
            this.parentNode.parentNode.children[1].children[0].value = '';
        }
    }

    // 修改密码按钮点击事件
    updatePwdBtn.onclick = function () {
        audioClickPlay();

        var oldPwd = settingWrap.querySelector('.update-pwd-wrap tr:first-of-type input').value;
        var newPwd = settingWrap.querySelector('.update-pwd-wrap tr:nth-of-type(2) input').value;
        var newPwd1 = settingWrap.querySelector('.update-pwd-wrap tr:nth-of-type(3) input').value;

        if (oldPwd == '') {
            popMessage('请输入旧密码');
            return;
        }
        if (newPwd == '' || newPwd1 == '') {
            popMessage('请输入新密码');
            return;
        }
        if (oldPwd.length < 6 || oldPwd.length > 20 || newPwd.length < 6 || newPwd.length > 20 || newPwd1.length < 6 || newPwd1 > 20) {
            popMessage('密码的长度为6-20位');
            return;
        }
        if (newPwd != newPwd1) {
            popMessage('2次输入的新密码不一致');
            return;
        }
        if (oldPwd === newPwd) {
            popMessage('旧密码和新密码相同');
            return;
        }
        popDialog('确认更新密码吗？', 2, function () {
            // 更新密码
            $.ajax({
                "url": "sql.asp",
                "type": "post",
                "data": {
                    action: 'updatePwd',
                    ID: gameDatas.ID,
                    oldPwd: oldPwd,
                    newPwd: newPwd
                },
                "dataType": "text",
                "success": function (data) {
                    var jsonData = JSON.parse(data)
                    if (jsonData.state === 'ok') {
                        // 更新密码成功
                        popMessage('密码修改成功');
                    } else if (jsonData.state === 'error') {
                        popMessage(jsonData.msg);
                    } else {
                        popMessage(ajaxDataError);
                    }
                },
                "error": function () {
                    popMessage(ajaxError);
                }
            });
        });
    }

    // 建议反馈模块
    var textarea = settingWrap.querySelector('.advise-wrap textarea');
    var adviseButton = settingWrap.querySelector('.advise-wrap button');

    adviseButton.onclick = function () {
        audioClickPlay();
        var value = textarea.value.trim();
        if (value === '') {
            popMessage('请输入内容后才可以发送');
            return;
        }

        $.ajax({
            "url": "sql.asp",
            "type": "post",
            "data": {
                action: 'advise',
                ID: gameDatas.ID,
                username: gameDatas.username,
                advise: value
            },
            "dataType": "text",
            "success": function (data) {
                var jsonData = JSON.parse(data)
                if (jsonData.state === 'ok') {
                    textarea.value = '';
                    popDialog('感谢您的反馈,我们将随后回复，祝您游戏愉快！', 1);
                } else {
                    popMessage(jsonData.msg);
                }
            }
        });
    }
}

// 升级土地模块
var infos;
var upgradeBtns;

function upgradeLandInit() {
    var upgradeLandPic = mainScene.querySelector('#upgrade-land-pic');
    var upgradeLandWrap = mainScene.querySelector('#upgrade-land-wrap');
    var btns = upgradeLandWrap.querySelectorAll('.title .btn');
    var items = upgradeLandWrap.querySelectorAll('.item');
    infos = upgradeLandWrap.querySelectorAll('.info');
    var landNum;

    upgradeBtns = upgradeLandWrap.querySelectorAll('.content button');

    upgradeLandPic.onclick = function () {
        audioClickPlay();
        upgradeLandWrap.style.display = 'block';
        closeSeedWrap();
        clearClickCircleView();

        gameDatas.plainLandNum = 0;
        gameDatas.redLandNum = 0;
        gameDatas.blackLandNum = 0;
        gameDatas.blueLandNum = 0;
        gameDatas.purpleLandNum = 0;
        gameDatas.goldLandNum = 0;
        var t = false;
        for (let i = 0; i < gameDatas.lands.length; i++) {
            switch (gameDatas.lands[i].type) {
                case 'grass':
                    t = true;
                    break;
                case 'lock':
                    t = true;
                    break;
                case 'gold':
                    gameDatas.goldLandNum++;
                case 'purple':
                    gameDatas.purpleLandNum++;
                case 'blue':
                    gameDatas.blueLandNum++;
                case 'black':
                    gameDatas.blackLandNum++;
                case 'red':
                    gameDatas.redLandNum++;
                case 'plain':
                    gameDatas.plainLandNum++;
            }
            if (t) {
                break;
            }
        }
        landNum = [gameDatas.redLandNum, gameDatas.blackLandNum, gameDatas.blueLandNum, gameDatas.purpleLandNum, gameDatas.goldLandNum];
        if (gameDatas.redLandNum === 24) {
            infos[0].innerHTML = '红土地增产20%，增加经验10%。恭喜，所有的红土地已全部升级完啦！';
            upgradeBtns[0].disabled = true;
            upgradeBtns[0].innerHTML = '升级完成';
        } else if (gameDatas.level < gameDatas.redLevel) {
            infos[0].innerHTML = '红土地增产20%，增加经验10%。升级第' + (gameDatas.redLandNum + 1) + '块红土地需要' + gameDatas.redLevel + '级、金币' + gameDatas.redCoin + '，对不起，您的等级不足。';
            upgradeBtns[0].disabled = true;
        } else if (gameDatas.coin < gameDatas.redCoin) {
            infos[0].innerHTML = '红土地增产20%，增加经验10%。升级第' + (gameDatas.redLandNum + 1) + '块红土地需要' + gameDatas.redLevel + '级、金币' + gameDatas.redCoin + '，对不起，您的金币不足。';
            upgradeBtns[0].disabled = true;
        } else if (gameDatas.redLandNum === gameDatas.plainLandNum || gameDatas.redLevel === -1) {
            infos[0].innerHTML = '红土地增产20%，增加经验10%。暂无可升级的红土地，请先扩建土地！';
            upgradeBtns[0].disabled = true;
        } else {
            infos[0].innerHTML = '红土地增产20%，增加经验10%。升级第' + (gameDatas.redLandNum + 1) + '块红土地需要' + gameDatas.redLevel + '级、金币' + gameDatas.redCoin + '，是否要升级？';
            upgradeBtns[0].disabled = false;
        }

        if (gameDatas.blackLandNum === 24) {
            infos[1].innerHTML = '黑土地增产40%，增加经验20%。恭喜，所有的黑土地已全部升级完啦！';
            upgradeBtns[1].disabled = true;
            upgradeBtns[1].innerHTML = '升级完成';
        } else if (gameDatas.level < gameDatas.blackLevel) {
            infos[1].innerHTML = '黑土地增产40%，增加经验20%。升级第' + (gameDatas.blackLandNum + 1) + '块黑土地需要' + gameDatas.blackLevel + '级、金币' + gameDatas.blackCoin + '，对不起，您的等级不足。';
            upgradeBtns[1].disabled = true;
        } else if (gameDatas.coin < gameDatas.blackCoin) {
            infos[1].innerHTML = '黑土地增产40%，增加经验20%。升级第' + (gameDatas.blackLandNum + 1) + '块黑土地需要' + gameDatas.blackLevel + '级、金币' + gameDatas.blackCoin + '，对不起，您的金币不足。';
            upgradeBtns[1].disabled = true;
        } else if (gameDatas.blackLandNum === gameDatas.redLandNum || gameDatas.blackLevel === -1) {
            infos[1].innerHTML = '黑土地增产40%，增加经验20%。暂无可升级的黑土地，请先升级红土地！';
            upgradeBtns[1].disabled = true;
        } else {
            infos[1].innerHTML = '黑土地增产40%，增加经验20%。升级第' + (gameDatas.blackLandNum + 1) + '块黑土地需要' + gameDatas.blackLevel + '级、金币' + gameDatas.blackCoin + '，是否要升级？';
            upgradeBtns[1].disabled = false;
        }

        if (gameDatas.blueLandNum === 24) {
            infos[2].innerHTML = '蓝土地增产60%，增加经验30%。恭喜，所有的蓝土地已全部升级完啦！';
            upgradeBtns[2].disabled = true;
            upgradeBtns[2].innerHTML = '升级完成';
        } else if (gameDatas.level < gameDatas.blueLevel) {
            infos[2].innerHTML = '蓝土地增产60%，增加经验30%。升级第' + (gameDatas.blueLandNum + 1) + '块蓝土地需要' + gameDatas.blueLevel + '级、金币' + gameDatas.blueCoin + '，对不起，您的等级不足。';
            upgradeBtns[2].disabled = true;
        } else if (gameDatas.coin < gameDatas.blueCoin) {
            infos[2].innerHTML = '蓝土地增产60%，增加经验30%。升级第' + (gameDatas.blueLandNum + 1) + '块蓝土地需要' + gameDatas.blueLevel + '级、金币' + gameDatas.blueCoin + '，对不起，您的金币不足。';
            upgradeBtns[2].disabled = true;
        } else if (gameDatas.blueLandNum === gameDatas.blackLandNum || gameDatas.blueLevel === -1) {
            infos[2].innerHTML = '蓝土地增产60%，增加经验30%。暂无可升级的蓝土地，请先升级黑土地！';
            upgradeBtns[2].disabled = true;
        } else {
            infos[2].innerHTML = '蓝土地增产60%，增加经验30%。升级第' + (gameDatas.blueLandNum + 1) + '块蓝土地需要' + gameDatas.blueLevel + '级、金币' + gameDatas.blueCoin + '，是否要升级？';
            upgradeBtns[2].disabled = false;
        }

        if (gameDatas.purpleLandNum === 24) {
            infos[3].innerHTML = '紫土地增产80%，增加经验40%。恭喜，所有的紫土地已全部升级完啦！';
            upgradeBtns[3].disabled = true;
            upgradeBtns[3].innerHTML = '升级完成';
        } else if (gameDatas.level < gameDatas.purpleLevel) {
            infos[3].innerHTML = '紫土地增产80%，增加经验40%。升级第' + (gameDatas.purpleLandNum + 1) + '块紫土地需要' + gameDatas.purpleLevel + '级、金币' + gameDatas.purpleCoin + '，对不起，您的等级不足。';
            upgradeBtns[3].disabled = true;
        } else if (gameDatas.coin < gameDatas.purpleCoin) {
            infos[3].innerHTML = '紫土地增产80%，增加经验40%。升级第' + (gameDatas.purpleLandNum + 1) + '块紫土地需要' + gameDatas.purpleLevel + '级、金币' + gameDatas.purpleCoin + '，对不起，您的金币不足。';
            upgradeBtns[3].disabled = true;
        } else if (gameDatas.purpleLandNum === gameDatas.blueLandNum || gameDatas.purpleLevel === -1) {
            infos[3].innerHTML = '紫土地增产80%，增加经验40%。暂无可升级的紫土地，请先升级蓝土地！';
            upgradeBtns[3].disabled = true;
        } else {
            infos[3].innerHTML = '紫土地增产80%，增加经验40%。升级第' + (gameDatas.purpleLandNum + 1) + '块紫土地需要' + gameDatas.purpleLevel + '级、金币' + gameDatas.purpleCoin + '，是否要升级？';
            upgradeBtns[3].disabled = false;
        }

        if (gameDatas.goldLandNum === 24) {
            infos[4].innerHTML = '金土地增产100%，增加经验50%。恭喜，所有的金土地已全部升级完啦！';
            upgradeBtns[4].disabled = true;
            upgradeBtns[4].innerHTML = '升级完成';
        } else if (gameDatas.level < gameDatas.goldLevel) {
            infos[4].innerHTML = '金土地增产100%，增加经验50%。升级第' + (gameDatas.goldLandNum + 1) + '块金土地需要' + gameDatas.goldLevel + '级、金币' + gameDatas.goldCoin + '，对不起，您的等级不足。';
            upgradeBtns[4].disabled = true;
        } else if (gameDatas.coin < gameDatas.goldCoin) {
            infos[4].innerHTML = '金土地增产100%，增加经验50%。升级第' + (gameDatas.goldLandNum + 1) + '块金土地需要' + gameDatas.goldLevel + '级、金币' + gameDatas.goldCoin + '，对不起，您的金币不足。';
            upgradeBtns[4].disabled = true;
        } else if (gameDatas.goldLandNum === gameDatas.purpleLandNum || gameDatas.goldLevel === -1) {
            infos[4].innerHTML = '金土地增产100%，增加经验50%。暂无可升级的金土地，请先升级紫土地！';
            upgradeBtns[4].disabled = true;
        } else {
            infos[4].innerHTML = '金土地增产100%，增加经验50%。升级第' + (gameDatas.goldLandNum + 1) + '块金土地需要' + gameDatas.goldLevel + '级、金币' + gameDatas.goldCoin + '，是否要升级？';
            upgradeBtns[4].disabled = false;
        }
    }

    for (let i = 0; i < btns.length; i++) {
        btns[i].onclick = function () {
            audioClickPlay();
            this.parentNode.querySelector('.btn.active').classList.remove('active');
            this.classList.add('active');
            items[i].parentNode.querySelector('.item.active').classList.remove('active');
            items[i].classList.add('active');
        }
    }

    // 关闭按钮
    upgradeLandWrap.querySelector('.close').onclick = function () {
        audioClickPlay();
        upgradeLandWrap.style.display = 'none';
    }
    var landTypeArr = ['red', 'black', 'blue', 'purple', 'gold'];
    var landTypeArr1 = ['红', '黑', '蓝', '紫', '金'];
    // 升级土地
    for (let i = 0; i < upgradeBtns.length; i++) {
        upgradeBtns[i].onclick = function () {
            $.ajax({
                "url": "sql.asp",
                "type": "post",
                "data": {
                    action: 'upgradeLand',
                    ID: gameDatas.ID,
                    landIndex: landNum[i],
                    type: i
                },
                "dataType": "text",
                "success": function (data) {
                    var jsonData = JSON.parse(data)
                    if (jsonData.state === 'ok') {
                        upgradeLandWrap.style.display = 'none';
                        gameDatas.lands[landNum[i]].type = landTypeArr[i];
                        drawLandAndCrop();
                        addCoinNumber(jsonData.addCoin);
                        popMessage('<img src="images/land/land_' + landTypeArr[i] + '.png" style="width:1.6rem;height:0.8rem;vertical-align:middle;"> ' + landTypeArr1[i] + '土地 + 1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="images/main/coin.png" style="width:0.8rem;height:0.8rem;vertical-align:middle;"> 金币 - ' + Math.abs(jsonData.addCoin));
                        audioReapPlay();
                        getUpgradeAfterDatas();
                    } else {
                        popMessage(jsonData.msg);
                    }
                }
            })
        }
    }
}

// 矿山模块
var minePic;
var mineInfo;

function mineInit() {
    minePic = mainScene.querySelector('#mine-pic');
    mineInfo = minePic.querySelector('.info');

    minePic.onclick = function () {
        audioClickPlay();
        if (gameDatas.mine > 0) {
            popMessage('矿场冷却中');
            return;
        }

        $.ajax({
            "url": "sql.asp",
            "type": "post",
            "data": {
                action: 'mine',
                ID: gameDatas.ID
            },
            "dataType": "text",
            "success": function (data) {
                var jsonData = JSON.parse(data)
                if (jsonData.state === 'ok') {
                    var mineCoin = jsonData.mineCoin;
                    addCoinNumber(mineCoin);
                    popMessage('采矿成功，获得 <img src="images/main/coin.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 金币 + ' + mineCoin);
                    mainScene.querySelector('.mine-ani').style.display = 'none';
                    audioReapPlay();

                    // 渲染可扩建土地提示
                    drawLandExtendFun(true);

                    gameDatas.mine = jsonData.mine;
                    gameDatas.mineTimer && clearInterval(gameDatas.mineTimer);
                    mineInfo.innerHTML = Math.floor(gameDatas.mine / 3600 % 60) + ":" + Math.floor(gameDatas.mine / 60 % 60) + ":" + Math.floor(gameDatas.mine % 60);
                    gameDatas.mineTimer = setInterval(() => {
                        gameDatas.mine--;
                        mineInfo.innerHTML = Math.floor(gameDatas.mine / 3600 % 60) + ":" + Math.floor(gameDatas.mine / 60 % 60) + ":" + Math.floor(gameDatas.mine % 60);
                        if (gameDatas.mine <= 0) {
                            clearTimeout(gameDatas.mineTimer);
                            mineInfo.innerHTML = '可收取';
                            mainScene.querySelector('.mine-ani').style.display = 'block';
                        }
                    }, 1000);
                } else {
                    popMessage(jsonData.msg);
                }
            }
        });
    }
}

signinPic.onclick = function () {
    audioClickPlay();
    if (gameDatas.isSignin) {
        popDialog('<div style="text-align:center;"><div style="font-size: 16px;">今天已经签到过了，明天再来哟！</div></div>', 1);
        return;
    }
    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'signin',
            ID: gameDatas.ID
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data)
            if (jsonData.state === 'ok') {
                if (jsonData.type === 'coin') {
                    addCoinNumber(jsonData.num);
                    popDialog('<div style="text-align:center;"><div style="font-size: 16px;">恭喜获得<br></divstyle=><img src="images/main/coin.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 金币 + ' + jsonData.num + '</div>', 1);
                    // 渲染可扩建土地提示
                    drawLandExtendFun(true);
                    gameDatas.isSignin = true;
                } else if (jsonData.type === 'exp') {
                    addExp(jsonData.num, jsonData.isUpgrade == 'true', jsonData.expMax);
                    popDialog('<div style="text-align:center;"><div style="font-size: 16px;">恭喜获得<br></divstyle=><img src="images/main/exp.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 经验 + ' + jsonData.num + '</div>', 1);
                    gameDatas.isSignin = true;
                } else if (jsonData.type === 'diamond') {
                    addDiamond(jsonData.num);
                    popDialog('<div style="text-align:center;"><div style="font-size: 16px;">恭喜获得<br></divstyle=><img src="images/main/diamond.png" style="width:0.8rem;height:0.8rem;vertical-align: middle;"> 钻石 + ' + jsonData.num + '</div>', 1);
                    gameDatas.isSignin = true;
                } else if (jsonData.type === 'seed') {
                    var seedID1 = jsonData.seedID1;
                    var seedID2 = jsonData.seedID2;
                    for (let i = 0; i < gameDatas.house.length; i++) {
                        if (gameDatas.house[i].ID === seedID1) {
                            gameDatas.house[i].number++;
                        }
                    }
                    for (let i = 0; i < gameDatas.house.length; i++) {
                        if (gameDatas.house[i].ID === seedID2) {
                            gameDatas.house[i].number++;
                        }
                    }
                    //渲染土地和其上的作物视图
                    drawLandAndCrop();
                    //取得 种子数组 和 作物数组
                    getSeedsAndCrops();
                    //渲染仓库视图
                    drawHouseAndGoods(houseCropOrSeedType);
                    //渲染背包种子视图
                    drawBagSeedView();

                    popDialog(`
                    <div style="text-align:center;">
                        <div style="font-size: 16px;">
                            恭喜获得
                            <div><img style="width:2rem;height:2rem;vertical-align: middle;" src="images/crop/${seedID1}.png" </div><br>${gameDatas.goods[findGoodIndexByGoodID(seedID1)].name} + 1<br>
                            <div><img style="width:2rem;height:2rem;vertical-align: middle;" src="images/crop/${seedID2}.png" </div><br>${gameDatas.goods[findGoodIndexByGoodID(seedID2)].name} + 1 
                        </div>
                    </div>
                    `, 1);
                    gameDatas.isSignin = true;
                }
            } else if (jsonData.state === 'done') {
                gameDatas.isSignin = true;
                popDialog('<div style="text-align:center;"><div style="font-size: 16px;">今天已经签到过了，明天再来哟！</div></div>', 1);
            } else if (jsonData.state === 'error') {
                popMessage(jsonData.msg);
            } else {
                popMessage(ajaxDataError);
            }
        },
        "error": function () {
            popMessage(ajaxError)
        }
    });
}

// 检测是否有用户的新回复
function checkReply() {
    $.ajax({
        "url": "sql.asp",
        "type": "post",
        "data": {
            action: 'checkReply',
            ID: gameDatas.ID
        },
        "dataType": "text",
        "success": function (data) {
            var jsonData = JSON.parse(data)
            if (jsonData.state === 'ok') {
                popDialog("<div>新回复：</div><div style='color:#0f0;font-size: 18px;'>" + jsonData.reply + "</div><div>是否要删除该消息？删除请点“√”，保留请点“×”</div>", 2, () => {
                    $.ajax({
                        "url": "sql.asp",
                        "type": "post",
                        "data": {
                            action: 'deleteReply',
                            ID: gameDatas.ID
                        },
                        "dataType": "text",
                        "success": function (data) {
                            var jsonData = JSON.parse(data)
                            if (jsonData.state === 'ok') {
                                popMessage('删除成功！');
                            } else if (jsonData.state === 'error') {
                                popMessage(jsonData.msg);
                            } else {
                                popMessage(ajaxDataError);
                            }
                        }
                    })
                });
            } else if (jsonData.state === 'error') {
                if (jsonData.msg === '没有新回复') {
                    return;
                }
                popMessage(jsonData.msg);
            } else {
                popMessage(ajaxDataError);
            }
        },
        "error": function () {
            popMessage(ajaxError)
        }
    });
}
